<script setup name="Lyrics">
import { lyrics } from '@/services/home'
import { ref, onMounted, computed, watch } from 'vue'

const props = defineProps({
  sId: {
    type: [Number, String],
    default: 0
  },
  currentTime: {
    type: Number,
    default: 0
  },
  maxH: {
    type: [Number, String],
    default: 400
  }
})

const lyric = ref(null)
const lyricObj = ref([])
const curIndex = ref(0)

const isCurLyric = computed(() => {
  return (index) => {
    return index === curIndex.value && props.currentTime ? 'active' : '';
  }
})

const getLyrics = async (id) => {
  const res = await lyrics(id)
  formartLyric(res.lrc)
}

const formartLyric = (lrc) => {
  const lrcReg = /^\[(\d{2}):(\d{2}.\d{2,})\]\s*(.+)$/;
  if (!lrc.lyric) {
    lyric.value = true
    return
  }
  const lyricLis = lrc.lyric.split('\n')
  lyric.value = lrc.lyric
  lyricLis.forEach(item => {
    const arr = lrcReg.exec(item)
    if (!arr) return
    lyricObj.value.push({ t: arr[1] * 60 + parseFloat(arr[2]), txt: arr[3] })
  })
  // 根据时间轴重排顺序
  lyricObj.value.sort((a, b) => {
    return a.t - b.t
  })
}

// 歌词实时滚动
const transform = computed(() => {
  if (curIndex.value > 6) {
    return `transform: translateY(-${30 * (curIndex.value - 6)}px)`;
  } else {
    return 'transform: translateY(0)';
  }
})

const findCurIndex = (t) => {
  for (let i = 0; i < lyricObj.value.length; i++) {
    if (t <= lyricObj.value[i].t) {
      return i
    }
  }
  return lyricObj.value.length
}

onMounted(() => getLyrics(props.sId))

watch(() => props.sId, (newVal) => {
  lyric.value = null
  lyricObj.value = []
  curIndex.value = 0
  getLyrics(newVal)
})

watch(() => props.currentTime, (newVal) => {
  // 无歌词的时候 不做动画滚动
  if (!lyricObj.value.length) {
    return
  }
  curIndex.value = findCurIndex(newVal) - 1
})
</script>

<template>
  <div class="lyrics-main" :style="{ maxHeight: maxH + 'px' }">
    <template v-if="lyricObj.length">
      <div class="lyrics" :style="transform" v-for="(i, index) in lyricObj" :key="index">
        <p :class="[isCurLyric(index)]">{{ i.txt }}</p>
      </div>
    </template>
    <div v-else class="lyric-empty">
      <p v-if="lyric">纯音乐，无歌词</p>
      <p v-else>歌词加载中......</p>
    </div>
  </div>
</template>

<style scoped lang="scss">
.lyrics-main {
  height: 100%;
  overflow-y: auto;
  transition: all 1.5s ease-in-out;

  .lyrics {
    text-align: center;
    font-size: 14px;
    transform: translateY(0);
    transition: transform 1.5s ease-in-out;

    :deep(p) {
      margin: 0;
      line-height: 30px;
      font-size: 14px;
      font-weight: 300;

      &.active {
        font-weight: bold;
        font-size: 20px;
      }
    }
  }

  .lyric-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-height: 100px;
    font-size: 14px;
    color: var(--color-text-height);
  }
}
</style>